import * as request from "superagent";
import { Logger } from "@nestjs/common";


export class RequestService {
    private static readonly logger = new Logger(RequestService.name);

    private static getClient(method: string, ...params: any[]) {
        const [url, headers, timeout, retry] = params;
        const client = request(method, url);
        if (headers) {
            client.set(headers);
        }
        if (timeout) {
            client.timeout(timeout);
        }
        if (retry) {
            client.retry(retry);
        }
        return client;
    }

    public static async get(url: string, headers?: any, timeout?: number, retry?: number) {
        const client = this.getClient('GET', url, headers, timeout, retry);
        try {   
            const res = await client;
            if (res.ok) {
                return res.text;
            }
            this.logger.error(`Get (${url}) failed, ${res.text}`);
        } catch (error) {
            this.logger.error(`Get (${url}) unexcept exception, ${error}`);
        }
        return null;
    }

    public static async post(url: string, payload: any, headers?: any, timeout?: number, retry?: number) {
        this.logger.debug(`Post (${url}) with payload: ${JSON.stringify(payload)}`);
        const client = this.getClient('POST', url, headers, timeout, retry);
        try {
            const res = await client.send(payload);
            if (res.ok) {
                return res.text;
            }
            this.logger.error(`Post (${url}) failed, ${res.text}`);
        } catch (error) {
            this.logger.error(`Post (${url}) unexcept exception, ${error}`);
        }
    }
}
